package com.unitd.frame.springweb.interceptor;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @desc Spring	MVC的数据加载拦截器,用于提前对加载的数据进行过滤
 * @filename DataLoadingInterceptor.java
 * @copyright www.unitd.com
 * @author Hudan
 * @version 1.0
 * @date 2017/3/29
 */
public class DataLoadingInterceptor implements HandlerInterceptor {

	public DataLoadingInterceptor() {
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if(handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod)handler;
			if(handlerMethod.getBean() instanceof HandlerInterceptor) {
				return ((HandlerInterceptor)handlerMethod.getBean()).preHandle(request, response, handler);
			}
		}

		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		if(handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod)handler;
			if(handlerMethod.getBean() instanceof HandlerInterceptor) {
				((HandlerInterceptor)handlerMethod.getBean()).postHandle(request, response, handler, modelAndView);
			}
		}
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		if(handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod)handler;
			if(handlerMethod.getBean() instanceof HandlerInterceptor) {
				((HandlerInterceptor)handlerMethod.getBean()).afterCompletion(request, response, handler, ex);
			}
		}
	}
}